package test;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import tool.DBUtil;

public class PAY {
    private JFrame frame;
    private JCheckBox propertyFeeCheckBox;
    private JLabel propertyFeeStatusLabel;
    private JCheckBox waterFeeCheckBox;
    private JLabel waterFeeStatusLabel;
    private JCheckBox elecFeeCheckBox;
    private JLabel elecFeeStatusLabel;
    private Test1.User userData;
    public static double waterPricePerUnit; // 新增：水费单价
    public static double electricityPricePerUnit; // 新增：电费单价

    public PAY() {
        userData = Test1.getUserDataByUsername(Test1.user);

        // 从数据库获取水费和电费单价
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT wat, ele FROM `2025` WHERE month = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, 6); // 获取6月的数据
            rs = pstmt.executeQuery();

            if (rs.next()) {
                waterPricePerUnit = rs.getDouble("wat");
                electricityPricePerUnit = rs.getDouble("ele");
            } else {
                JOptionPane.showMessageDialog(frame, "无法获取水费和电费单价，请检查数据库", "错误", JOptionPane.ERROR_MESSAGE);
                waterPricePerUnit = 0.0; // 默认值
                electricityPricePerUnit = 0.0; // 默认值
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(frame, "数据库连接失败，请稍后再试", "错误", JOptionPane.ERROR_MESSAGE);
            waterPricePerUnit = 0.0; // 默认值
            electricityPricePerUnit = 0.0; // 默认值
        } finally {
            DBUtil.closeConnection(conn);
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        frame = new JFrame("费用缴纳通知");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        frame.setLayout(new GridLayout(6, 2)); // 修改布局为6行2列，使每行两个组件

        // 添加窗口监听器，监听关闭事件
        frame.addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent e) {
                new MannageService().setVisible(true); // 修改: 返回MannageService页面
            }
        });

        // 物业费相关组件
        propertyFeeCheckBox = new JCheckBox("物业费：  " + Test1.propertyFeeUsage);
        frame.add(propertyFeeCheckBox);
        String propertyFeeStatus = userData.getPropertyFeeStatus() != null ? userData.getPropertyFeeStatus() : "0";
        propertyFeeStatusLabel = new JLabel(propertyFeeStatus.equals("0") ? "未缴" : "已缴");
        frame.add(propertyFeeStatusLabel);

        // 新增判断：若缴费状态为1，则禁用复选框
        if ("1".equals(propertyFeeStatus)) {
            propertyFeeCheckBox.setEnabled(false);
        }

        // 水费相关组件
        waterFeeCheckBox = new JCheckBox("水费：   "  + (Test1.waterUsage * waterPricePerUnit));
        frame.add(waterFeeCheckBox);
        String waterFeeStatus = userData.getWaterFeeStatus() != null ? userData.getWaterFeeStatus() : "0";
        waterFeeCheckBox.setEnabled(waterFeeStatus.equals("0"));
        waterFeeStatusLabel = new JLabel(waterFeeStatus.equals("0") ? "未缴" : "已缴");
        frame.add(waterFeeStatusLabel);

        // 新增判断：若缴费状态为1，则禁用复选框
        if ("1".equals(waterFeeStatus)) {
            waterFeeCheckBox.setEnabled(false);
        }

        // 电费相关组件
        elecFeeCheckBox = new JCheckBox("电费：   " + (Test1.electricityUsage * electricityPricePerUnit));
        frame.add(elecFeeCheckBox);
        String electricityFeeStatus = userData.getElectricityFeeStatus() != null ? userData.getElectricityFeeStatus() : "0";
        elecFeeCheckBox.setEnabled(electricityFeeStatus.equals("0"));
        elecFeeStatusLabel = new JLabel(electricityFeeStatus.equals("0") ? "未缴" : "已缴");
        frame.add(elecFeeStatusLabel);

        // 新增判断：若缴费状态为1，则禁用复选框
        if ("1".equals(electricityFeeStatus)) {
            elecFeeCheckBox.setEnabled(false);
        }

        // 添加一个空面板用于占位
        frame.add(new JPanel());

        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        JButton payButton = new JButton("缴费");
        JButton detailsButton = new JButton("费用详情");
        JButton backButton = new JButton("返回"); // 新增返回按钮

        // 添加按钮到按钮面板
        buttonPanel.add(payButton);
        buttonPanel.add(detailsButton);
        buttonPanel.add(backButton); // 将返回按钮添加到按钮面板

        // 添加按钮面板到框架
        frame.add(buttonPanel);

        // 添加按钮事件监听器
        payButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 提示用户选择缴费项目
                StringBuilder selectedItems = new StringBuilder();
                if (propertyFeeCheckBox.isSelected()) {
                    selectedItems.append("物业费 ");
                }
                if (waterFeeCheckBox.isSelected()) {
                    selectedItems.append("水费 ");
                }
                if (elecFeeCheckBox.isSelected()) {
                    selectedItems.append("电费 ");
                }

                if (selectedItems.length() == 0) {
                    JOptionPane.showMessageDialog(frame, "请选择至少一个缴费项目", "提示", JOptionPane.INFORMATION_MESSAGE);
                    return;
                }

                // 确认缴费
                int confirm = JOptionPane.showConfirmDialog(frame, "您选择了以下项目：" + selectedItems.toString() + "\n确认缴费吗？", "确认缴费", JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    // 更新数据库中的缴费状态
                    updatePaymentStatus();

                    // 更新界面显示
                    updateStatusLabel(propertyFeeCheckBox, propertyFeeStatusLabel, "物业费");
                    updateStatusLabel(waterFeeCheckBox, waterFeeStatusLabel, "水费");
                    updateStatusLabel(elecFeeCheckBox, elecFeeStatusLabel, "电费");

                    JOptionPane.showMessageDialog(frame, "缴费成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                }
            }
        });

        // 修改 detailsButton 的事件监听器
        detailsButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 调用 PaymentDetails 的 main 方法，跳转到费用详情界面
                PaymentDetails.main(new String[0]);
            }
        });

        // 新增返回按钮的事件监听器
        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                frame.dispose(); // 关闭当前窗口
                new MannageService().setVisible(true); // 打开MannageService页面
            }
        });
    }

    // 新增方法：更新缴费状态
    private void updatePaymentStatus() {
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = DBUtil.getConnection();

            // 更新物业费状态
            if (propertyFeeCheckBox.isSelected()) {
                String sql = "UPDATE 关于用户 SET WuPayState = '1' WHERE User = ?";
                pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, Test1.user);
                pstmt.executeUpdate();
                pstmt.close();
            }

            // 更新水费状态
            if (waterFeeCheckBox.isSelected()) {
                String sql = "UPDATE 关于用户 SET WaterPayState = '1' WHERE User = ?";
                pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, Test1.user);
                pstmt.executeUpdate();
                pstmt.close();
            }

            // 更新电费状态
            if (elecFeeCheckBox.isSelected()) {
                String sql = "UPDATE 关于用户 SET ElecPayState = '1' WHERE User = ?";
                pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, Test1.user);
                pstmt.executeUpdate();
                pstmt.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(frame, "数据库更新失败，请稍后再试", "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            DBUtil.closeConnection(conn);
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 新增方法：更新状态标签
    private void updateStatusLabel(JCheckBox checkBox, JLabel label, String feeType) {
        if (checkBox.isSelected()) {
            label.setText("已缴");
            checkBox.setEnabled(false);
        }
    }

    public static void main(String[] args) {
        PAY pay = new PAY();
        pay.frame.setVisible(true);
    }
}